package com.sneakxy.cloudbase.platform.utils.web;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import io.swagger.annotations.ApiParam;
import lombok.Data;

/**
 * 分页查询
 * @author 潜行的青衣
 * @see
 */
@Data
public class PageSearch<T> {

	@ApiParam(name="pageNumber", value="第几页", required=true)
	private int pageNumber;
	
	@ApiParam(name="pageSize", value="每页记录数", required=true)
	private int pageSize;
	
	@ApiParam(name="search", value="查询关键字")
	private T search;
	
	@ApiParam(name="sortName", value="排序字段名")
	private String sortName;
	
	@ApiParam(name="sortOrder", value="排序类型:asc、desc", defaultValue="asc")
	private String sortOrder = "asc";
	
	public Pageable toPageable() {
		Sort sort = null;
		PageRequest pageable = null; 
		int page = this.pageNumber > 0 ? this.pageNumber - 1 : 0;
		if(StringUtils.isNotBlank(this.sortName)) {
			sort = Sort.by(StringUtils.equalsIgnoreCase("desc", sortOrder) ? Direction.DESC : Direction.ASC, StringUtils.trimToEmpty(sortName));
			pageable = PageRequest.of(page, this.pageSize, sort);
		} else {
			pageable = PageRequest.of(page, this.pageSize);
		}
		return pageable;
	}
	
	public <M> PageSearch<M> toPageSearch(M search) {
		PageSearch<M> result = new PageSearch<>();
		result.setPageNumber(pageNumber);
		result.setPageSize(pageSize);
		result.setSortName(sortName);
		result.setSortOrder(sortOrder);
		result.setSearch(search);
		return result;
	}

}
